//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package fs_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/fs_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type FsStatusDbItem struct {
	FileCount     uint32 `bson:"fileCount"`
	TotalFileSize uint64 `bson:"totalFileSize"`
}

type FsInfoDbItem struct {
	FsId         string         `bson:"_id"`
	OwnerType    int32          `bson:"ownerType"`
	OwnerId      string         `bson:"ownerId"`
	Status       FsStatusDbItem `bson:"status"`
	MaxFilecount uint32         `bson:"maxFilecount"`
	MaxTotalSize uint64         `bson:"maxTotalSize"`
	LastGcTime   int64          `bson:"lastGcTime"`
}

func (item *FsInfoDbItem) ToFsStatus() *fs_api.FsStatus {
	return &fs_api.FsStatus{
		FsId:          item.FsId,
		OwnerType:     fs_api.FS_OWNER_TYPE(item.OwnerType),
		OwnerId:       item.OwnerId,
		FileCount:     item.Status.FileCount,
		TotalFileSize: item.Status.TotalFileSize,
		MaxFilecount:  item.MaxFilecount,
		MaxTotalSize:  item.MaxTotalSize,
		LastGcTime:    item.LastGcTime,
	}
}

type _FsInfoDao struct {
	mc *mongo.Collection
}

func newFsInfoDao(db *mongo.Database) (*_FsInfoDao, error) {
	mc := db.Collection(db_ns.DB_NS_FS + "info")
	return &_FsInfoDao{mc: mc}, nil
}

func (db *_FsInfoDao) Insert(ctx context.Context, dbItem *FsInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_FsInfoDao) Get(ctx context.Context, fsId string) (*FsInfoDbItem, error) {
	retItem := &FsInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": fsId}).Decode(retItem)
	return retItem, err
}

func (db *_FsInfoDao) Exist(ctx context.Context, fsId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": fsId})
	return count > 0, err
}

func (db *_FsInfoDao) Remove(ctx context.Context, fsId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": fsId})
	return err
}

func (db *_FsInfoDao) ListById(ctx context.Context, fsIdList []string) ([]*FsInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": fsIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*FsInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_FsInfoDao) IncStatus(ctx context.Context, fsId string, newFilecount, newFileSize int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": fsId}, bson.M{"$inc": bson.M{"status.fileCount": newFilecount, "status.totalFileSize": newFileSize}})
	return err
}

func (db *_FsInfoDao) UpdateLastGcTime(ctx context.Context, fsId string, lastGcTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": fsId}, bson.M{"$set": bson.M{"lastGcTime": lastGcTime}})
	return err
}
